import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/task.dart';
import '../providers/task_provider.dart';
import '../providers/member_filter_provider.dart';
import 'task_card.dart';
import 'package:dotted_border/dotted_border.dart';
import '../models/member.dart';
import '../providers/member_provider.dart';
import '../providers/auth_provider.dart';

class TaskList extends StatefulWidget {
  final bool showCompleted;
  final String searchQuery;

  const TaskList({
    super.key, 
    this.showCompleted = false,
    this.searchQuery = '',
  });

  @override
  State<TaskList> createState() => _TaskListState();
}

class _TaskListState extends State<TaskList> with SingleTickerProviderStateMixin {
  Task? _draggedTask;
  int? _draggedIndex;
  String _sortBy = 'created';
  bool _ascending = false;
  late AnimationController _rotationController;
  bool _isDragging = false;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      Provider.of<TaskProvider>(context, listen: false).loadTasks();
      Provider.of<MemberProvider>(context, listen: false).loadMembers();
    });
    
    _rotationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
  }

  @override
  void dispose() {
    _rotationController.dispose();
    super.dispose();
  }

  List<Task> _sortTasks(List<Task> tasks) {
    try {
      var sortedTasks = List<Task>.from(tasks);
      switch (_sortBy) {
        case 'created':
          sortedTasks.sort((a, b) => _ascending
              ? a.createdAt.compareTo(b.createdAt)
              : b.createdAt.compareTo(a.createdAt));
          break;
        case 'due':
          sortedTasks.sort((a, b) {
            if (a.dueDate == null) return _ascending ? -1 : 1;
            if (b.dueDate == null) return _ascending ? 1 : -1;
            return _ascending
                ? a.dueDate!.compareTo(b.dueDate!)
                : b.dueDate!.compareTo(a.dueDate!);
          });
          break;
        case 'priority':
          sortedTasks.sort((a, b) => _ascending
              ? a.priority.index.compareTo(b.priority.index)
              : b.priority.index.compareTo(a.priority.index));
          break;
      }
      return sortedTasks;
    } catch (e) {
      print('Error sorting tasks: $e');
      return tasks;
    }
  }

  void _toggleSortDirection() {
    setState(() {
      _ascending = !_ascending;
    });
    if (_ascending) {
      _rotationController.forward();
    } else {
      _rotationController.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer3<TaskProvider, MemberFilterProvider, MemberProvider>(
      builder: (context, taskProvider, filterProvider, memberProvider, child) {
        if (taskProvider.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        // 获取任务列表
        var tasks = taskProvider.tasks;

        // 应用成员筛选
        if (filterProvider.selectedRole != null) {
          tasks = tasks.where((task) {
            if (task.assignedTo == null) return false;
            final member = memberProvider.getMemberById(task.assignedTo!);
            return member?.role == filterProvider.selectedRole;
          }).toList();
        }

        // 应用完成状态筛选
        tasks = widget.showCompleted 
            ? tasks.where((task) => task.isCompleted).toList()
            : tasks.where((task) => !task.isCompleted).toList();

        // 应用搜索筛选
        if (widget.searchQuery.isNotEmpty) {
          tasks = tasks.where((task) => 
            task.title.toLowerCase().contains(widget.searchQuery.toLowerCase())
          ).toList();
        }

        // 应用排序
        tasks = _sortTasks(tasks);

        if (tasks.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  widget.searchQuery.isEmpty
                      ? (widget.showCompleted ? Icons.check_circle : Icons.list)
                      : Icons.search_off,
                  size: 64,
                  color: Colors.grey,
                ),
                const SizedBox(height: 16),
                Text(
                  widget.searchQuery.isEmpty
                      ? (widget.showCompleted ? '无已完成任务' : '暂无待办任务')
                      : '未找到匹配的任务',
                  style: const TextStyle(
                    fontSize: 18,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          );
        }

        return Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  // 添加成员筛选
                  Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    constraints: const BoxConstraints(
                      maxWidth: 200,
                      minWidth: 120,
                    ),
                    child: GestureDetector(
                      onTap: () {
                        showDialog(
                          context: context,
                          builder: (context) {
                            return AlertDialog(
                              title: const Text('选择成员'),
                              content: Consumer2<MemberProvider, TaskProvider>(
                                builder: (context, memberProvider, taskProvider, child) {
                                  // 获取有任务的成员
                                  final membersWithTasks = memberProvider.members.where((member) {
                                    return taskProvider.tasks.any((task) => task.assignedTo == member.id);
                                  }).toList();

                                  if (membersWithTasks.isEmpty) {
                                    return const Center(
                                      child: Text('暂无任务分配给任何成员'),
                                    );
                                  }

                                  return SingleChildScrollView(
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        // 所有成员选项
                                        ListTile(
                                          leading: const Icon(Icons.people),
                                          title: const Text('所有成员'),
                                          selected: filterProvider.selectedRole == null,
                                          onTap: () {
                                            filterProvider.setRole(null);
                                            Navigator.pop(context);
                                          },
                                        ),
                                        const Divider(),
                                        // 只显示有任务的成员
                                        ...membersWithTasks.map((member) => ListTile(
                                          leading: const Icon(Icons.person),
                                          title: Text(member.name),
                                          selected: filterProvider.selectedRole == member.role,
                                          onTap: () {
                                            filterProvider.setRole(member.role);
                                            Navigator.pop(context);
                                          },
                                        )),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            );
                          },
                        );
                      },
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Icon(Icons.person, size: 20),
                          const SizedBox(width: 4),
                          Consumer<MemberFilterProvider>(
                            builder: (context, filterProvider, child) {
                              return Flexible(
                                child: Text(
                                  () {
                                    if (filterProvider.selectedRole == null) return '所有成员';
                                    return filterProvider.getRoleName(filterProvider.selectedRole);
                                  }(),
                                  style: const TextStyle(fontSize: 14),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              );
                            },
                          ),
                          const Icon(Icons.arrow_drop_down),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  // 排序选项
                  Container(
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: _isDragging 
                            ? Colors.grey.shade200  // 拖拽时变灰
                            : Colors.grey.shade300,
                      ),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: PopupMenuButton<String>(
                      enabled: !_isDragging,  // 拖拽时禁用
                      initialValue: _sortBy,
                      tooltip: _isDragging ? '拖拽时无法排序' : '选择排序方式',
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            _sortBy == 'created' ? '创建时间' :
                            _sortBy == 'due' ? '截止日期' : '优先级',
                            style: TextStyle(
                              fontSize: 14,
                              color: _isDragging ? Colors.grey : null,  // 拖拽时变灰
                            ),
                          ),
                          Icon(
                            Icons.arrow_drop_down,
                            color: _isDragging ? Colors.grey : null,  // 拖拽时变灰
                          ),
                        ],
                      ),
                      onSelected: (value) {
                        if (value != _sortBy) {
                          setState(() {
                            _sortBy = value;
                            _ascending = false;
                          });
                          _rotationController.reset();
                        }
                      },
                      itemBuilder: (context) => [
                        const PopupMenuItem(
                          value: 'created',
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.access_time, size: 20),
                              SizedBox(width: 8),
                              Flexible(
                                child: Text(
                                  '创建时间',
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const PopupMenuItem(
                          value: 'due',
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.event, size: 20),
                              SizedBox(width: 8),
                              Flexible(
                                child: Text(
                                  '截止日期',
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const PopupMenuItem(
                          value: 'priority',
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.priority_high, size: 20),
                              SizedBox(width: 8),
                              Flexible(
                                child: Text(
                                  '优先级',
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  IconButton(
                    icon: RotationTransition(
                      turns: Tween(begin: 0.0, end: 0.5)
                          .animate(_rotationController),
                      child: Icon(
                        Icons.arrow_downward,
                        color: _isDragging ? Colors.grey : null,  // 拖拽时变灰
                      ),
                    ),
                    onPressed: _isDragging ? null : _toggleSortDirection,  // 拖拽时禁用
                    tooltip: _isDragging 
                        ? '拖拽时无法切换排序方向' 
                        : (_ascending ? '升序' : '降序'),
                  ),
                ],
              ),
            ),
            // 任务列表
            Expanded(
              child: Stack(
                children: [
                  GridView.builder(
                    padding: const EdgeInsets.all(16),
                    gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 300,
                      childAspectRatio: 1,
                      crossAxisSpacing: 16,
                      mainAxisSpacing: 16,
                    ),
                    itemCount: tasks.length,
                    itemBuilder: (context, index) {
                      final task = tasks[index];
                      return DragTarget<Task>(
                        onWillAccept: (draggedTask) {
                          // 基本条件检查
                          if (draggedTask == null || 
                              draggedTask == task || 
                              draggedTask.isCompleted != task.isCompleted || 
                              _sortBy != 'priority') {
                            return false;
                          }
                          return true;  // 允许任意位置的交换
                        },
                        onAccept: (draggedTask) {
                          final taskProvider = Provider.of<TaskProvider>(
                            context, 
                            listen: false,
                          );
                          
                          // 直接交换位置
                          if (_sortBy == 'priority') {
                            taskProvider.reorderTask(draggedTask.id, task.position);
                          } else {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('请切换到优先级排序以重新排列任务'),
                                duration: Duration(seconds: 2),
                              ),
                            );
                          }
                        },
                        builder: (context, candidateData, rejectedData) {
                          return Stack(
                            children: [
                              TaskCard(
                                task: task,
                                onDragStarted: () {
                                  if (_sortBy != 'priority') {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text('请切换到优先级排序以重新排列任务'),
                                        duration: Duration(seconds: 2),
                                      ),
                                    );
                                    return;
                                  }
                                  setState(() {
                                    _draggedTask = task;
                                    _isDragging = true;
                                  });
                                },
                                onDragEnd: (details) {
                                  setState(() {
                                    _draggedTask = null;
                                    _isDragging = false;
                                  });
                                },
                              ),
                              if (candidateData.isNotEmpty)
                                Container(
                                  decoration: BoxDecoration(
                                    color: Colors.blue.withOpacity(0.2),
                                    border: Border.all(
                                      color: Colors.blue,
                                      width: 2,
                                    ),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: const Center(
                                    child: Icon(
                                      Icons.swap_horiz,
                                      color: Colors.blue,
                                      size: 36,
                                    ),
                                  ),
                                ),
                            ],
                          );
                        },
                      );
                    },
                  ),
                  if (_draggedTask != null)
                    Align(
                      alignment: widget.showCompleted 
                          ? Alignment.topCenter 
                          : Alignment.bottomCenter,
                      child: Container(
                        height: 100,
                        margin: const EdgeInsets.all(16),
                        child: DragTarget<Task>(
                          onWillAccept: (draggedTask) {
                            return draggedTask != null && 
                                   draggedTask.isCompleted != widget.showCompleted;
                          },
                          onAccept: (draggedTask) {
                            final taskProvider = Provider.of<TaskProvider>(
                              context, 
                              listen: false,
                            );
                            taskProvider.toggleTaskCompletion(draggedTask);
                          },
                          builder: (context, candidateData, rejectedData) {
                            if (candidateData.isEmpty) return const SizedBox();
                            return Container(
                              decoration: BoxDecoration(
                                color: Colors.green.withOpacity(0.2),
                                border: Border.all(
                                  color: Colors.green,
                                  width: 2,
                                ),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Center(
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Icon(
                                      widget.showCompleted 
                                          ? Icons.radio_button_unchecked 
                                          : Icons.check_circle,
                                      color: Colors.green,
                                      size: 32,
                                    ),
                                    const SizedBox(height: 8),
                                    Text(
                                      widget.showCompleted 
                                          ? '标记为未完成' 
                                          : '标记为已完成',
                                      style: const TextStyle(
                                        color: Colors.green,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }
} 